package cn.edu.zjgsu.ito.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.json.JSONObject;
import com.alibaba.fastjson.JSON;

import cn.edu.zjgsu.ito.interceptor.AdminControllerInterceptor;
import cn.edu.zjgsu.ito.service.AdminManageScoreService;
import cn.edu.zjgsu.ito.service.CourseEndService;
import cn.edu.zjgsu.ito.service.CourseService;
import cn.edu.zjgsu.ito.service.ServiceFactory;
import cn.edu.zjgsu.ito.service.StuInfService;
import cn.edu.zjgsu.ito.service.StuScoreService;
import cn.edu.zjgsu.ito.service.TeaInfService;
import cn.edu.zjgsu.ito.service.TeaStuService;
import cn.edu.zjgsu.ito.service.TeaTimetableService;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;


@Before(AdminControllerInterceptor.class)
public class AdminManageScoreController extends Controller {
	/**
	 * 管理员成绩管理
	 * 2016.11.04
	 * */

	private CourseService courseService =ServiceFactory.createCourseService();
	private TeaInfService teaInfService =ServiceFactory.createTeaInfService();
	private CourseEndService courseEndService =ServiceFactory.createCourseEndService();
	private TeaTimetableService teaTimetableService =ServiceFactory.createTeaTimetableService();
	private StuScoreService stuScoreService =ServiceFactory.createStuScoreService();
	private StuInfService stuInfoService =ServiceFactory.createStuInfService();
	private TeaStuService teaStuService =ServiceFactory.createTeaStuService();
	private AdminManageScoreService adminManageScoreService = ServiceFactory.createAdminManageScoreService();
	private List<Record> Records;
	private List<Record> Record1;
	private List<Record> Record2;
	private List<Record> Record3;
	private Record record;
	public static final DateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");

	private String termValue;
	private String course;
	private String teacher;
	private List<Record> termValues;

	public void index(){
		Record1=courseService.allCourse();	//获取所有课程
		setAttr("allCourse",Record1);

		Record2=teaInfService.allTeacher(); //获取所有教师
		setAttr("allTeacher",Record2);

		termValues=teaTimetableService.AllTerm();//获取所有学期
		setAttr("termValues",termValues);

		List<Record> stuInfo = adminManageScoreService.getStudentInfo();//获取所有学生个人信息
		setAttr("stuInfo",stuInfo);

		//判断课程是否超时
		adminManageScoreService.timeJudge();

		ArrayList<Record> allTest = (ArrayList<Record>) adminManageScoreService.allTest();//获取所有考试的课程
		setAttr("allTest",allTest);

		ArrayList<Record> allTTT = (ArrayList<Record>) adminManageScoreService.index();//获取所有课程

		courseDeal(allTTT);

		render("scoreManage/scoremanage.html");

	}

	/**
	 * 成绩管理初始页面
	 */
	public void courseDeal(List<Record> Record){

		setAttr("allTTT",Record);

	}

	/**
	 * 条件搜索
	 */
	public void tjsearch(){
		termValue=getPara("termValue");
		String courseNo=getPara("course");
		teacher=getPara("teacher");
		//		Records=teaTimetableService.selectTTT(termValue, teacher, courseNo);
		if(termValue == null || courseNo == null || teacher == null){
			termValue = "0";
			courseNo = "0";
			teacher = "0";
		}
		Records = adminManageScoreService.tjsearch(termValue,courseNo,teacher);
		courseDeal(Records);
		renderJson(Records);
	}

	/**
	 * 学生成绩详情
	 */
	public void stuScore(){
		try{
			String testNo;
			testNo = getPara("testNo");
			ArrayList<Record> allStuGra = (ArrayList<Record>) adminManageScoreService.stuScore(testNo);
			//成绩类型判断
			String gradeType = "";
			if(allStuGra.get(0).getStr("grade") != null){
				String gradeTypeStr = allStuGra.get(0).getStr("grade");
				if(gradeTypeStr.equals("A") || gradeTypeStr.equals("B") || gradeTypeStr.equals("C") || gradeTypeStr.equals("P") || gradeTypeStr.equals("F")){
					gradeType = "F";
				}else{
					gradeType = "H";
				}
			}
			setAttr("gradeType",gradeType);
			setAttr("testNo",testNo);
			setAttr("allStuGra",allStuGra);
			render("scoreManage/coursescoremanage.html");

		}catch(Exception e){
			e.printStackTrace();
		}


	}
	//一门课程对应建立一门考试,新建一门课程的时候 对应有一门考试，需要补考的时候  建立一门考试   自动增加补考的考试名单
	/**
	 * 生成补考
	 * */
	public void addTest(){
		String uuid;
		uuid = getPara("uuid");
		System.out.println(uuid+"=====");
		String temp = "";
		int res = adminManageScoreService.addTest(uuid);//生成一门考试
		if(res == 1){
			String temptt = "生成补考成功。";
			temp=JsonKit.toJson(temptt);
		}else if(res == 2){
			String temptt = "不符合添加补考条件。";
			temp=JsonKit.toJson(temptt);
			renderJson(temp);
		}else if(res == 3){
			String temptt = "已经生成了补考。";
			temp=JsonKit.toJson(temptt);
			renderJson(temp);
		}
	}



	/**
	 * 截止时间修改
	 * @throws ParseException 
	 */
	public void changeTimeAll(){

		String termValue=getPara("setSel");
		String courseNo=getPara("thetermValue");
		String changeTime=getPara("changeTime");

		//		String termValue = "2015/2016(1)";
		//		String courseNo = "0";
		//		String changeTime = "2016-11-25";

		adminManageScoreService.changeTimeAll(termValue,courseNo,changeTime);
		tjsearch();
		//		index();
		//		adminLock();
		//所有课程截止时间修改
	}

	/**
	 * 处理锁   判断单一修改还是 解锁处理时间
	 * */
	public void adminLock(){
		String testNo = getPara("testNo");
		String changeTime = getPara("changeTime2");
		System.out.println(testNo+"========="+changeTime);
		adminManageScoreService.adminLock(testNo,changeTime);
		tjsearch();
	}

	/**
	 * 导出提交的成绩
	 */
	public void exportGrade(){

		System.out.println("导出成绩");
		String testNo = getPara("testNo") ;
		Record test = Db.findFirst("select * from test,teacher_info where test.tNo=teacher_info.tNo and testNo=?",testNo);
		String termValue = test.getStr("termValue");
		String term = termValue.replace("/","-");
		String courseNo = test.getStr("courseNo");
		String tNo = test.getStr("tNo");
		String tName = test.getStr("tName");
		OutputStream out = null;
		Date date = new Date();
		String time=formatter.format(date);

		System.out.println(time);

		String filedir=PathKit.getWebRootPath();
		filedir=filedir+"\\WEB-INF\\download\\";
		deleteFile(new File(filedir));//清空缓存区

		String temp = term + courseNo + tNo + tName + time +".xls";
		String outpath = filedir+temp;
		try {
			out = new FileOutputStream(outpath);
			adminManageScoreService.exportGrade(testNo,out);
			renderFile(new File(outpath));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	 		
	}

	//按学生姓名查看成绩，返回学生json
	public void lookStuInfo(){
		List<Record> stuInfo = adminManageScoreService.getStudentInfo();
		String stuInfoJson = "";
		stuInfoJson = JsonKit.toJson(stuInfo);
		renderJson(stuInfoJson);
	}

	//成绩管理补考页面跳转
	public void lookBukaoStuGrades(){
		String testNo = getPara("testNo");
		String uuid = getPara("uuid");
		System.out.println("uuid"+uuid);
		List<Record> gradeSystem = adminManageScoreService.lookSystem(uuid);
		List<Record> stuGradeInfo = adminManageScoreService.lookStuGrades(testNo);
		String gradeType = "";
		for(int i = 0;i < gradeSystem.size();i++ ){
			if(gradeSystem.get(i).getStr("grade") != null && !(gradeSystem.get(i).getStr("grade").equals("旷考") || gradeSystem.get(i).getStr("grade").equals("作弊"))){
				String gradeTypeStr = gradeSystem.get(i).getStr("grade");
				System.out.println("成绩状态:" + gradeTypeStr);
				if(gradeTypeStr.equals("A") || gradeTypeStr.equals("B") || gradeTypeStr.equals("C") || gradeTypeStr.equals("P") || gradeTypeStr.equals("F")){
					gradeType = "F";
					break;
				}else{
					gradeType = "H";
					break;
				}
			}
		}
		System.out.println("成绩类型:" + gradeType);
		setAttr("gradeType",gradeType);
		setAttr("testNo",testNo);
		setAttr("stuGradeInfo",stuGradeInfo);
		render("scoreManage/scorebukaomanage.html");
	}

	//修改学生成绩具体信息
	public void updateStudentGrade(){
		String passportNo = getPara("passportNo");
		String testNo = getPara("testNo");
		String dailyGrade = getPara("dailyGrade");
		String experimentalGrade = getPara("experimentalGrade");
		String otherGrade = getPara("otherGrade");
		String finalGrade = getPara("finalGrade");
		String grade = getPara("grade");//补考传来的成绩
		adminManageScoreService.updateStudentGrade(passportNo,testNo,dailyGrade,experimentalGrade,otherGrade,finalGrade,grade);
		
	}

	public void deleteFile(File oldPath) {
		if (oldPath.isDirectory()) {
			File[] files = oldPath.listFiles();
			for (File file : files) {
				deleteFile(file);
			}
		}else{
			oldPath.delete();
		}
	}

}
